package com.gitee.chessboard.jdbc.parser;

import com.gitee.chessboard.jdbc.JdbcManager;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 将对象转换成insert的sql
 *
 * @author 敲代码的旺财
 * @date 2021/11/25 13:37
 */
public class InsertParser implements Parser {

    /**
     * jdbc的管理器
     */
    JdbcManager jdbcManager;

    public InsertParser(JdbcManager jdbcManager) {
        this.jdbcManager = jdbcManager;
    }

    /**
     * 将对象转成创建表的sql
     *
     * @param obj 需要解析的对象
     * @return 建表sql语句
     */
    @Override
    public String convert(Object obj) {
        ParserHandler parserHandler = jdbcManager.getParserHandler(obj);
        Set<Map.Entry<String, String>> entries = parserHandler.getTableFieldNameAndFieldName().entrySet();
        StringBuilder sb = new StringBuilder("INSERT INTO " + parserHandler.getTableName());
        sb.append(" (");
        sb.append(entries.stream().map(Map.Entry::getKey).collect(Collectors.joining(",")));
        sb.append(" )");
        sb.append(" values(");
        sb.append(entries.stream().map(m->"#{"+m.getValue()+"}").collect(Collectors.joining(",")));
        sb.append(" )");
        return sb.toString();
    }

}
